package com.jbp.utils.payUtils;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.jbp.model.AlipayConfig;

public class AlipayUtils {
    /**获取支付宝支付信息
     * */
    public static String getAliPayInfo(String goodName,String orderNo, String money, AlipayConfig alipayConfig, String notifyUrl) {
//        money="0.01";
        Factory.setOptions(getOptions(alipayConfig, notifyUrl));
        try {
            AlipayTradeAppPayResponse response = Factory.Payment.App()
                    .pay(goodName, orderNo, money);
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
//                System.out.println("调用成功");
//                System.out.println(response.body);
                return  response.body;
            } else {
                System.err.println("调用失败，原因：" + response.toString() + "，" + response.body);
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }

    public static Config getOptions(AlipayConfig alipayConfig, String notifyUrl) {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipay.com";
        config.signType = "RSA2";
        config.appId = alipayConfig.getAppid();

        //好呀
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        //config.merchantPrivateKey = propertyService.getV("alipay_merchant_private_key");
        config.merchantPrivateKey = alipayConfig.getMerchantPrivateKey();

        //config.alipayPublicKey = propertyService.getV("alipay_public_key");
        config.alipayPublicKey = alipayConfig.getPublicKey();

        //可设置异步通知接收服务地址（可选）
        config.notifyUrl = notifyUrl;

        return config;
    }
}
